package br.com.halyson.pontoeletronico.view;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import br.com.halyson.pontoeletronico.R;
import br.com.halyson.pontoeletronico.controller.Utils;
import br.com.halyson.pontoeletronico.dao.DataHelper;
import br.com.halyson.pontoeletronico.model.PontoDia;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;

public class PontoActivity extends SherlockFragment
{
    private TextView tvTime, tvDate, tvDayExtensive;
    
    private CheckBox statusPontoEntrada, statusPontoSaidaAlmoco, statusPontoVoltaAlmoco, statusPontoSaida;
    
    private Button btnMarcarPonto, btnAdicionarNota;
    
    private Utils utls;
    
    private Timer timer;
    
    private DataHelper db;
    
    private PontoDia pontoDia;
    
    @Override
    public SherlockFragmentActivity getSherlockActivity()
    {
        return super.getSherlockActivity();
    }
    
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.ponto_activity, container, false);
        utls = new Utils();
        
        tvTime = (TextView) view.findViewById(R.id.tvHora);
        tvDate = (TextView) view.findViewById(R.id.tvDate);
        tvDayExtensive = (TextView) view.findViewById(R.id.tvDayExtensive);
        
        statusPontoEntrada = (CheckBox) view.findViewById(R.id.cbStatusEntrada);
        statusPontoSaidaAlmoco = (CheckBox) view.findViewById(R.id.cbStatusPontoSaidaAlmoco);
        statusPontoVoltaAlmoco = (CheckBox) view.findViewById(R.id.cbStatusPontoVoltaAlmoco);
        statusPontoSaida = (CheckBox) view.findViewById(R.id.cbStatusSaida);
        
        btnMarcarPonto = (Button) view.findViewById(R.id.btnMarcaPonto);
        btnAdicionarNota = (Button) view.findViewById(R.id.btnAdicionarNota);
        
        db = new DataHelper(getSherlockActivity());
        pontoDia =
            db.selectAllByDay(utls.getCurrentDateDay() + "." + utls.getCurrentDateMonth() + "." + utls.getCurrentDateYear());
        
        if (pontoDia.getEntrada())
        {
            statusPontoEntrada.setButtonDrawable(R.drawable.ponto_marcado);
        }
        if (pontoDia.getSaida_almoco())
        {
            statusPontoSaidaAlmoco.setButtonDrawable(R.drawable.ponto_marcado);
        }
        if (pontoDia.getVolta_almoco())
        {
            statusPontoVoltaAlmoco.setButtonDrawable(R.drawable.ponto_marcado);
        }
        if (pontoDia.getSaida())
        {
            statusPontoSaida.setButtonDrawable(R.drawable.ponto_marcado);
        }
        
        if (db.selectByNoteDayIsExist(utls.getCurrentDateDay() + "." + utls.getCurrentDateMonth() + "."
                + utls.getCurrentDateYear()))
        {
            btnAdicionarNota.setText("Mostrar Nota");
        }
        else
        {
            btnAdicionarNota.setText("Adicionar Nota");
        }
        
        btnMarcarPonto.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                
                db = new DataHelper(getSherlockActivity());
                pontoDia =
                    db.selectAllByDay(utls.getCurrentDateDay() + "." + utls.getCurrentDateMonth() + "."
                            + utls.getCurrentDateYear());
                
                if ((!pontoDia.getEntrada()) && (!pontoDia.getSaida_almoco()) && (!pontoDia.getVolta_almoco())
                        && (!pontoDia.getSaida()))
                {
                    statusPontoEntrada.setButtonDrawable(R.drawable.ponto_marcado);
                    utls.insertPonto("entrada", getSherlockActivity());
                }
                else if ((pontoDia.getEntrada()) && (!pontoDia.getSaida_almoco()) && (!pontoDia.getVolta_almoco())
                        && (!pontoDia.getSaida()))
                {
                    statusPontoSaidaAlmoco.setButtonDrawable(R.drawable.ponto_marcado);
                    utls.insertPonto("saida_almoco", getSherlockActivity());
                }
                else if ((pontoDia.getEntrada()) && (pontoDia.getSaida_almoco()) && (!pontoDia.getVolta_almoco())
                        && (!pontoDia.getSaida()))
                {
                    statusPontoVoltaAlmoco.setButtonDrawable(R.drawable.ponto_marcado);
                    utls.insertPonto("volta_almoco", getSherlockActivity());
                }
                else if ((pontoDia.getEntrada()) && (pontoDia.getSaida_almoco()) && (pontoDia.getVolta_almoco())
                        && (!pontoDia.getSaida()))
                {
                    statusPontoSaida.setButtonDrawable(R.drawable.ponto_marcado);
                    utls.insertPonto("saida", getSherlockActivity());
                }
                else if ((pontoDia.getEntrada()) && (pontoDia.getSaida_almoco()) && (pontoDia.getVolta_almoco())
                        && (pontoDia.getSaida()))
                {
                    Toast.makeText(getSherlockActivity(), "Você já realizou todas marcações do dia!", Toast.LENGTH_SHORT).show();
                    Utils.copyDataBaseToSD(getSherlockActivity());                    
                }
            }
        });
        
        btnAdicionarNota.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                db = new DataHelper(getSherlockActivity());
                
                if (btnAdicionarNota.getText().equals("Adicionar Nota"))
                {
                    AlertDialog.Builder dialogAdicionarNotas = new AlertDialog.Builder(getSherlockActivity());
                    dialogAdicionarNotas.setTitle("Nota");
                    dialogAdicionarNotas.setMessage("Insira a justificativa da nota !");
                    dialogAdicionarNotas.setIcon(R.drawable.new_note);
                    
                    final EditText input = new EditText(getSherlockActivity());
                    dialogAdicionarNotas.setView(input);
                    
                    dialogAdicionarNotas.setPositiveButton("Confirmar", new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog, int whichButton)
                        {
                            btnAdicionarNota.setText("Mostrar Notas");
                            utls.insertNota(String.valueOf(input.getText()), getSherlockActivity());
                        }
                    });
                    
                    dialogAdicionarNotas.setNegativeButton("Cancelar", new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog, int whichButton)
                        {
                            dialog.cancel();
                        }
                    });
                    
                    AlertDialog alertDialog = dialogAdicionarNotas.create();
                    alertDialog.show();
                }
                else
                {
                    AlertDialog.Builder dialogNotaDia = new AlertDialog.Builder(getSherlockActivity());
                    dialogNotaDia.setTitle("Nota");
                    dialogNotaDia.setIcon(R.drawable.new_note);
                    dialogNotaDia.setMessage(utls.selectNota(getSherlockActivity()));
                    
                    dialogNotaDia.setPositiveButton("OK", new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog, int whichButton)
                        {
                        }
                    });
                    
                    dialogNotaDia.setCancelable(false);
                    
                    AlertDialog alertDialog = dialogNotaDia.create();
                    alertDialog.show();
                }
            }
        });
        return view;
    }
    
    @Override
    public void onStart()
    {
        super.onStart();
        timer = new Timer();
        Calendar calendar = Calendar.getInstance();
        
        // Recupera Tempo Corrente
        final Runnable updateTask = new Runnable()
        {
            public void run()
            {
                // Exibe o tempo
                tvTime.setText(utls.getCurrentTimeHour() + ":" + utls.getCurrentTimeMinute());
                tvDate.setText(utls.getCurrentDateDay() + "." + utls.getCurrentDateMonth() + "." + utls.getCurrentDateYear());
                tvDayExtensive.setText(utls.getCurrentDateDayExtensive());
            }
        };
        
        // Atualiza a UI
        int msec = 999 - calendar.get(Calendar.MILLISECOND);
        timer.scheduleAtFixedRate(new TimerTask()
        {
            @Override
            public void run()
            {
                getSherlockActivity().runOnUiThread(updateTask);
            }
        }, msec, 20000);
    }
    
    @Override
    public void onResume()
    {
        super.onResume();
        db = new DataHelper(getSherlockActivity());
        PontoDia pontoDia =
            db.selectAllByDay(utls.getCurrentDateDay() + "." + utls.getCurrentDateMonth() + "." + utls.getCurrentDateYear());
        
        if (pontoDia.getEntrada())
        {
            statusPontoEntrada.setButtonDrawable(R.drawable.ponto_marcado);
        }
        if (pontoDia.getSaida_almoco())
        {
            statusPontoSaidaAlmoco.setButtonDrawable(R.drawable.ponto_marcado);
        }
        if (pontoDia.getVolta_almoco())
        {
            statusPontoVoltaAlmoco.setButtonDrawable(R.drawable.ponto_marcado);
        }
        if (pontoDia.getSaida())
        {
            statusPontoSaida.setButtonDrawable(R.drawable.ponto_marcado);
        }
    }
    
    @Override
    public void onStop()
    {
        super.onStop();
        
        // Pausa a Thread
        timer.cancel();
        timer.purge();
        timer = null;
    }
    
}